package com.web_bloks.generators.rebind;

import java.io.PrintWriter;
import java.util.Iterator;

import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JPackage;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;

/**
 * Retrieves the ScreenModule list from the
 * ScreenModuleManager and produces a dynamic implementation 
 * for the type 'ScreensList' 
 *  
 * @author Jean-Lou Dupont
 *
 */
public class ScreensListGenerator extends Generator {

	public String generate(TreeLogger logger, GeneratorContext context, String typeName) 
		throws UnableToCompleteException {


	    JClassType slType = null;
	    try {
	      slType = context.getTypeOracle().getType(typeName);
	    } catch (NotFoundException e) {
	      logger.log(TreeLogger.ERROR, "Cannot find ["+typeName+"] class", e);
	      throw new UnableToCompleteException();
	    }

	    JPackage pkg = slType.getPackage();
	    String className = slType.getName();
		
	    logger.log(TreeLogger.DEBUG, "packageName["+pkg.getName()+"] className["+className+"]" );
	    
		//SourceWriter sw = getSourceWriter(logger, context, pkg.getName(), className );
		ScreenModuleManager smm = new ScreenModuleManager();
		logger.log(TreeLogger.DEBUG, "got ScreenManagerModule["+smm+"]" );
		
		Iterator<String> i = ScreenModuleManager.liste.iterator();
		logger.log(TreeLogger.DEBUG, "got iterator["+i+"]" );
		
		while(i.hasNext()) {
			String classe = i.next();
			logger.log(TreeLogger.INFO, "found ["+classe+"]");
		}
	
		return null;
	}
	
	/**
	 * Queries the ScreenModuleManager for its list
	 * and builds up a type containing the list
	 */
	protected void generateScreensListClass() {

		
	}

	protected SourceWriter getSourceWriter(TreeLogger logger, GeneratorContext context, 
			String packageName, String className) {
		
	    PrintWriter printWriter = context.tryCreate(logger, packageName, className);
	    if (printWriter == null) {
	      return null;
	    }
	    ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, className);
	    composerFactory.addImport("com.google.gwt.core.client.GWT");

	    return composerFactory.createSourceWriter(context, printWriter);
	  }

}//END